<?php
declare(strict_types=1);

namespace Service\GoodsBrandService;

use Service\BaseService;
use Service\CountryService\CountryService;
use Service\Code\Normal;
use Service\HelperService\Common;
use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\Country;
use Service\CacheService\CacheProviderService as Cache;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * 商品品牌
 * @author hj
 */
class BrandService extends BaseService {

    /**
     * 获取品牌信息
     */
    public static function getBrand(array $ids): array {
        if (empty($ids)) {
            return [];
        }
        $result = [];
        //获取品牌国家信息
        $countrys = CountryService::getCountry();
        $allBrand = GoodsBrand::whereIn('id', $ids)->where('df', 0)->select(['id', 'country_id', 'name', 'pic'])->get()->toArray();
        if (!$allBrand) {
            return $result;
        }
        $allBrand = array_column($allBrand, null, 'id');
        foreach ($ids as $id) {
            $cache_key = "GoodsBrand_GetBrand_{$id}";
            $brand     = Cache::getCacheByKey($cache_key);
            if (!empty($brand)) {
                $result[$id] = $brand;
                continue;
            }
            $brand = $allBrand[$id] ?? [];
            if (empty($brand)) {
                continue;
            }
            $brand['country_name'] = !empty($countrys[$brand['country_id']]['name']) ? $countrys[$brand['country_id']]['name'] : '';
            $brand['country_icon'] = !empty($countrys[$brand['country_id']]['icon']) ? $countrys[$brand['country_id']]['icon'] : '';
            if (!empty($brand['pic']) && strpos($brand['pic'], 'http') === false) {
                $brand['pic'] = Common::$pre_image_url . $brand['pic'];
            }
            if (!empty($brand['country_icon']) && strpos($brand['country_icon'], 'http') === false) {
                $brand['country_icon'] = Common::$pre_image_url . $brand['country_icon'];
            }
            if (strpos($brand['name'], '其他') !== false) {
                $brand['name']         = '';
                $brand['country_name'] = '';
                $brand['country_icon'] = '';
            }
            $brand['isChina'] = $brand['country_name'] == '中国' ? 1 : 0;
            Cache::cacheBySetKeyValue($cache_key, $brand, 300);
            $result[$id] = $brand;
        }
        return $result;
    }
}